<template>
    <div class="container" v-cloak>
        <div class="blurBg" :style="{background:'url('+blurBg+') 0 0 no-repeat'}"></div>
        <div class="dataInfo">
            <div class="inputModel">
                <div class="inputTitle Semibold font13">作业内容</div>
                <textarea class="titleInput" ref="textarea" placeholder="请输入作业内容" v-model="content" maxlength="2000"></textarea>
                <div class="inputLimit"><span v-text="content.length"></span>/2000</div>
            </div>
            <div class="uploadModel">
                <div class="uploadTitle Semibold font13" flex="cross:bottom">
                    <div>作业上传</div>
                    <div class="font10 uploadNum">(<span v-text="uploadList.length+oldList.length":style="{color:uploadList.length>0?'#1dc6b4':''}"></span>/9)</div>
                </div>
                <ul class="uploadList">
                    <li class="uploadAdd" flex="main:center cross:center" v-if="uploadList.length+oldList.length<9"
                        @click="showAdd()">
                        <img src="../../images/addIcon.png" class="addIcon"/>
                    </li>
                    <li flex v-for="(list,index) in oldList" class="picesWrap" @click="showPicesSwiper(list,index)">
                        <img :src="list.imgUrl+'?imageView2/0/w/136/format/jpeg'" v-if="list.type==1">
                        <img :src="list.imgUrl+'?vframe/jpeg/offset/1/w/136'" v-if="list.type==3">
                        <div class="audioWrapper" v-if="list.type==2">
                            <img src="../../images/audioBg.png"/>
                            <div class="audioTime" flex="main:center cross:center">
                                <span v-text="list.time>=60?parseInt(list.time/60):0" flex-box="0"></span>
                                <span flex-box="0">:</span>
                                <span v-text="parseInt(list.time%60)>=10?parseInt(list.time%60):'0'+parseInt(list.time%60)"
                                      flex-box="0"></span>
                            </div>
                        </div>
                        <img src="../../images/play.png" class="play" v-if="list.type==3"/>
                        <div class="removeIcon" @click.stop="deleteItem(index,oldList,true)" v-if="canUploadClick"></div>
                    </li>
                    <li flex v-for="(list,index) in uploadList" class="picesWrap"  @click="showPicesSwiper(list,index)">
                        <img :src="list.datathumbnail" v-if="list.datatype!=2"/>
                        <img src="../../images/play.png" class="play" v-if="list.datatype==3"/>
                        <div class="audioWrapper" v-if="list.datatype==2">
                            <img src="../../images/audioBg.png"/>
                            <div class="audioTime" flex="main:center cross:center">
                                <span v-text="list.datatime>=60?parseInt(list.datatime/60):0" flex-box="0"></span>
                                <span flex-box="0">:</span>
                                <span v-text="parseInt(list.datatime%60)>=10?parseInt(list.datatime%60):'0'+parseInt(list.datatime%60)"
                                      flex-box="0"></span>
                            </div>
                        </div>
                        <div class="removeIcon" @click.stop="deleteItem(index,uploadList,false)" v-if="canUploadClick"></div>
                    </li>
                </ul>
            </div>
            <div class="allSendBtn"  flex="main:center cross:center" @click="submit">提交</div>
        </div>
        <add-model ref="addModel" @addFuc="changeFile"></add-model>
        <div class="uploadWrapper" v-if="!canUploadClick"></div>
    </div>
</template>
<script type="text/babel">
    import API from '../../../api/api.js'
    import {domain,imagedomain} from '../../../api/api.js'
    import addModel from '../../../components/addModel.vue'
    const api = new API();
    export default{
        data(){
            return {
                isPicSubmit:false,
                //是否提交附件
                imagedomain:imagedomain,
                //七牛图片地址域名
                content: '',
                //提交作业内容
                uploadList:[],
                //新提交的附件
                allList:[],
                //所有的附件
                oldList:[],
                //提交过的附件
                classId: this.$route.query.classId?this.$route.query.classId:'',
                //班级id
                coreId: this.$route.query.coreId ? this.$route.query.coreId : '',
                //作业id
                replyId: this.$route.query.replyId ? this.$route.query.replyId : '',
                //回复作业id
                domain: domain,
                //域名
                imgKeys: [],
                //作业附件客户端传递的key
                canUploadClick: true,
                //是否可以提交作业(防止多次请求发布接口)
                isDetail:this.$route.query.isDetail ? this.$route.query.isDetail : ''
                //是否从详情页跳转到此页面
            }
        },
        mounted(){
            if (this.replyId) {
                this.searchStudentMultiwork();
            }
            if(this.isDetail!==''){
                this.$util.jsBridgeCallBack('jsLeftAction', this.$util.goBack);
            }else{
                this.$util.jsBridgeCallBack('jsLeftAction', this.closeWebView);
            }
            this.$nextTick(function(){
                setTimeout(()=>{
                    this.propsTitle();
                },300);
                document.documentElement.scrollTop=1;
                document.body.scrollTop=1;
            })
        },
        components:{
            addModel,
            //添加附件组件
        },
        methods: {
            /**
             * @describe jsBridge 查看已提交添加附件大图
             *
             * @date     2017-8-3
             *
             * @param    pices 附件数组
             *
             * @param    index 附件索引
             *
             * @author   langwenqi
             */
            clientSwiper(pices, index){
                if (this.canUploadClick) {
                    let arr = Array.prototype.toString.call(pices) === '[object String]' ? JSON.parse(JSON.stringify(JSON.parse(pices))) : JSON.parse(JSON.stringify(pices))
                    arr.forEach(function (e) {
                        e.imgUrl =  e.imgUrl;
                        if (e.type == 3) {
                            e.coverUrl = e.imgUrl + '?vframe/jpeg/offset/1';
                        }
                    });
                    //TODO:客户端浏览文件
                    this.$util.JsBridge('picesSwiper', {
                        picesList: arr,
                        picesIndex: index
                    }, (res) => {
                    })
                }
            },
            /**
             * @describe 查看已提交作业
             *
             * @date     2017-8-3
             *
             * @param    coreId 作业id
             *
             * @param    coreDetailId 回复作业id
             *
             * @author   langwenqi
             */
            searchStudentMultiwork(){
                let param={
                    coreId:this.coreId,
                    coreDetailId:this.replyId
                };
                api.searchStudentMultiwork(param).then(res=>{
                    let {code,rs}=res;
                    if(code==200){
                        if(rs.pices&&rs.pices.length>0){
                            this.oldList=rs.pices;
                            if(rs.studentDetail&&rs.studentDetail.content!==''){
                                this.content = this.$util.entitiestoUtf16(rs.studentDetail.content).replace(/<br>/ig,'\n').replace(/&nbsp;/g, ' ');
                            }
                        }
                    }else{
                        this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/submit',api:'searchStudentMultiwork',success:false,data:res}));
                    }
                }).catch(()=>{
                    this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/submit',api:'searchStudentMultiwork',success:false,data:'网络异常'}));
                })
            },
            /**
             * @describe jsBridge 关闭webView
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            closeWebView(){

                this.$util.JsBridge('closeWebView', {}, ()=> {})
            },
            /**
             * @describe 显示添加附件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            showAdd(){
                this.$refs.addModel.addShow=true;
            },
            closeAdd(){
                this.$refs.addModel.addShow=false;
            },
            propsTitle(){
                this.$util.JsBridge('propsTitle', {
                    title: '打卡作业',
                }, (res) => {
                })
            },
            /**
             * @describe 删除附件
             *
             * @param    index 附件索引
             *
             * @param    pices 作业附件数组
             *
             * @param    ifOld 是否为已提交附件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            deleteItem(index, pices, ifOld){
                this.$delete(pices, index);
                if (ifOld)return;
                this.$util.JsBridge('removePicesItem', {
                    picItemIndex: index
                }, (res) => {
                })
            },
            /**
             * @describe jsBridge 查看添加附件大图
             *
             * @date     2017-8-3
             *
             * @param    index 附件索引
             *
             * @author   langwenqi
             */
            seePicesItem(index){
                this.$util.JsBridge('seePicesItem', {
                    picItemIndex: index
                }, (res)=> {
                })
            },
            showPicesSwiper(pic,index){
                let newIndex;
                let arr=[];
                if(pic.datatype){
                    newIndex=this.oldList.length+index;
                }else{
                    newIndex=index;
                }
                this.oldList.forEach((el)=>{
                    let newEl={from:2,type:el.type,imgUrl:el.imgUrl,time:el.time};
                    if (el.type == 3) {
                        newEl.coverUrl = el.imgUrl + '?vframe/jpeg/offset/1';
                    }
                    arr.push(newEl);
                });
                this.uploadList.forEach((el)=>{
                    let newEl={from:1,type:el.type,imgUrl:el.imgUrl,time:el.time};
                    arr.push(newEl);
                });
                this.$util.JsBridge('showPicesSwiper', {
                    picesList: arr,
                    picesIndex: newIndex
                }, (res) => {
                })
            },

        /**
             * @describe 客户端上传文件
             *
             * @date     2017-8-3
             *
             * @param    picItemCount 附件上传限制张数
             *
             * @param    type 附件上传类型
             *
             * @param    appType APP_MULTI_WORK
             *
             * @author   langwenqi
             */
            changeFile(type){
                //TODO:客户端上传文件
                if (9 - (this.oldList.length+this.uploadList.length) > 0) {
                    this.$util.JsBridge('getPicesList', {
                        picItemCount: 9 - (this.oldList.length+this.uploadList.length),
                        showType: type,
                        appType: 'APP_MULTI_WORK'
                    }, (res)=> {
                        this.changeFileCallBack(res);
                        this.closeAdd();
                    })
                } else {
                    this.$toast('您最多只能上传9个附件');
                }
            },
            /**
             * @describe 客户端上传文件
             *
             * @date     2017-8-3
             *
             * @param    res 附件的key(类型Array)
             *
             * @author   langwenqi
             */
            changeFileCallBack(res){
                this.imgKeys = res;
                for (let i = 0; i < res.length; i++) {
                    this.getImgInfo(res[i])
                }
            },
            /**
             * @describe 通过key获取客户端文件
             *
             * @date     2017-8-3
             *
             * @param    rs 单个附件的key
             *
             * @author   langwenqi
             */
            getImgInfo(rs){
                this.$util.JsBridge('getImgInfo', {
                    fileKey: rs
                }, (res) => {
                    if (res.datathumbnail&&res.datathumbnail.indexOf('data:image/png;base64') == -1) {
                        res.datathumbnail = 'data:image/png;base64,' + res.datathumbnail;
                    }
                    res.imgUrl=rs;
                    res.type=res.datatype;
                    if(res.datatime){
                        res.time=res.datatime;
                    }
                    this.uploadList.push(res);
                })
            },
            /**
             * @describe 提交作业
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            submit() {
                if (this.uploadList.length + this.oldList.length == 0) {
                    this.$toast('作业附件不能为空');
                    return;
                }
                if (!this.canUploadClick) {
                    this.$toast('提交中,请稍后');
                    return;
                }
                if (this.uploadList.length + this.oldList.length <= 9) {
                    this.canUploadClick = false;
                    if (this.uploadList.length <= 0) {
                        this.submitMultiwork(this.oldList);
                        return;
                    }
                    if (this.isPicSubmit) {
                        this.submitMultiwork(this.allList);
                        return;
                    }
                    this.$util.JsBridge('submitFinish', {}, (result) => {
                        if (result.statuscode == 400) {
                            this.$toast('上传失败,请重新上传');
                            this.canUploadClick = true;
                        } else {
                            this.isPicSubmit = true;
                            let newResult = Object.prototype.toString.call(result) === '[object String]' ? JSON.parse(result) : result;
                            this.allList = this.oldList.concat(newResult);
                            this.submitMultiwork(this.allList);
                        }
                    })
                } else {
                    this.canUploadClick = true;
                    this.$toast('上传附件不能超过九张');
                }
            },
            /**
             * @describe 提交作业接口
             *
             * @param   content提交作业内容
             *
             * @param   classId班级id
             *
             * @param   coreId作业id
             *
             * @param   tid提交作业id
             *
             * @param   data作业附件
             *
             * @date     2017-8-3
             *
             * @author   langwenqi
             */
            submitMultiwork(allList){
                const content = this.$util.utf16toEntities(this.content).replace(/\n|\r\n/g, "<br>").replace(/[ ]/g, "&nbsp;");
                let param = {
                    content: content,
                    classId: this.classId,
                    coreId: this.coreId,
                    tid: this.replyId,
                    data: JSON.stringify(allList)
                };
                api.submitMultiwork(param).then((res) => {
                    let {code} = res;
                    if (code == 200) {
                        this.$toast('提交成功',true);
                        setTimeout(()=>{
                            this.$router.push({
                                path: '/app/multiwork/detail',
                                query: {classId: this.classId, role:1, appId: this.coreId}
                            })
                        },1000);
                    } else {
                        this.canUploadClick = true;
                        this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/submit',api:'submitMultiwork',success:false,data:res}));
                    }
                }).catch(()=>{
                    this.canUploadClick = true;
                    this.$util.sendLog(1,'APP_MULTI_WORK',JSON.stringify({time:new Date().Format('yyyy/MM/dd hh:mm'),name:'打卡作业',code:'APP_MULTI_WORK',path: '/app/multiwork/submit',api:'submitMultiwork',success:false,data:'网络异常'}));
                })
            },
        }
    }
</script>
<style scoped lang="scss">
    @keyframes float {
        0% {
            font-size:0.12rem;
            -webkit-transform: translate3d(0,0,0);
            transform: translate3d(0,0,0);
        }
        100% {
            font-size:0.1rem;
            -webkit-transform: translate3d(0,-0.2rem,0);
            transform: translate3d(0,-0.2rem,0);
        }
    }
    @keyframes floatOut {
        0% {
            font-size:0.1rem;
            -webkit-transform: translate3d(0,-0.2rem,0);
            transform: translate3d(0,-0.2rem,0);
        }
        100% {
            font-size:0.12rem;
            -webkit-transform: translate3d(0,0,0);
            transform: translate3d(0,0,0);
        }
    }
    .container {
        width: 100%;
        height: 100%;
        background: #000;
        position: relative;
    }

    .selectStudent{
        padding:0.28rem 0.12rem 0.1rem 0.12rem;
        .float{
            font-size:0.1rem;
            -webkit-animation:float 1s ease-out;
            animation: float 1s ease-out;
            -webkit-animation-fill-mode:forwards;
            animation-fill-mode:forwards;
            position: absolute;
        }
        .floatOrigin{
            font-size:0.12rem;
            -webkit-animation:floatOut 1s ease-out;
            animation: floatOut 1s ease-out;
            -webkit-animation-fill-mode:forwards;
            animation-fill-mode:forwards;
            position: absolute;
        }
        .studentList{
            margin-right:0.06rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .rightIcon{
            height:0.1rem;
            width: 0.1rem;
            background:url("../../images/iconMore.png") no-repeat right center/contain;
        }
    }
    .bottomLine{
        background: rgba(255,255,255,.2);
        width:3.5rem;
        height:1px;
        margin: 0 auto;

    }
    .inputModel {
        height: 1.83rem;
        width: 100%;
        padding-bottom: 0.13rem;
        border-bottom: 0.12rem solid rgba(0,0,0,0.5);
    }

    .inputTitle {
        padding: 0.12rem 0 0.12rem 0.12rem;
    }

    .inputLimit {
        opacity: 0.5;
        font-size: 0.1rem;
        text-align: right;
        margin-right: 0.12rem;
    }

    .titleInput {
        width: 100%;
        padding: 0 0.12rem;
        background: transparent;
        font-size: 0.13rem;
        color: #ffffff;
        height: 1rem;
    }

    .uploadTitle {
        padding: 0.17rem 0 0.12rem 0;
    }

    .uploadAdd {
        border: 1px dashed rgba(255,255,255,0.2);
        width: 0.8rem;
        height: 0.8rem;
    }

    .uploadModel {
        padding-left:0.12rem;
    }

    .addIcon {
        width: 0.23rem;
        height: 0.23rem;
    }

    .sendBtn {
        background:rgba(0,0,0,0.5);
        border-radius: 0.05rem;
        width: 1.80rem;
        height: 0.36rem;
        position: fixed;
        bottom: 0.22rem;
        color:#fff;
        left: 0;
        margin-left: 0.975rem;
        z-index: 99;
    }

    .picesWrap {
        background: #d8d8d8;
        position: relative;
        width: 0.8rem;
        height: 0.8rem;
        overflow: hidden;
        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            -o-object-fit: cover;
        }
    }

    .uploadList {
        overflow: hidden;
        li {
            position: relative;
            margin-bottom: 0.1rem;
            margin-right: 0.1rem;
            float: left;
        }
    }

    .inputWrap {
        width: 2.7rem;
        height: 0.81rem;
        position: relative;
        background: rgba(250, 251, 255, .1);
        textArea {
            width: calc(100% - 0.24rem);
            height: 100%;
            background: transparent;
            padding: 0.08rem 0 0 0.08rem;
            font-size: 0.12rem;
            color: #fff;
        }
    }

    .removeIcon {
        width: 0.18rem;
        height: 0.18rem;
        position: absolute;
        right: 0.04rem;
        top: 0.04rem;
        background: url("../../images/delete.png") no-repeat center center/cover;
    }

    .uploadNum {
        opacity: 0.5;
        margin-left: 0.08rem;
    }

</style>
